package newsComment

import (
	"gin/common/lib/gorm"
	"gin/dao/entity"
	"gin/model/body"
	"gin/util/stringify"
)

// Add 添加评论
func Add(p body.NewsCommentParam) {
	gorm.GinDb.SubTable("cmf_users_news_comment", p.NewsId).Create(&p)
}

// Del 删除评论
func Del(p body.DelNewsParam) {
	gorm.GinDb.SubTable("cmf_users_news_comment", p.NewId).
		Where("id  = ?", p.Id).Delete(&entity.NewsComment{})
}

func List(p body.NewsCommentListParam) []*entity.NewsCommentDetail {
	var list []*entity.NewsCommentDetail
	tableName := gorm.SubTable(gorm.GinDb, "cmf_users_news_comment", p.NewId)
	gorm.GinDb.Table(tableName+" as n").Select("n.*,u.user_nickname,u.avatar").
		Joins("left join cmf_users u on u.id = n.uid").
		Where("news_id = ?", p.NewId).
		Find(&list)
	return list
}

// UnreadNum 未读消息
func UnreadNum(uid int64) int64 {
	var allNum int64
	for i := 0; i < int(gorm.GinDb.Split); i++ {
		var num int64
		tableName := "cmf_users_news_comment_" + stringify.ToString(i)
		gorm.GinDb.Table("cmf_users_news n").
			Joins("left join "+tableName+" c on n.id = c.news_id").
			Where("n.uid = ? and c.is_read = 0 and c.uid != ?", uid, uid).Count(&num)
		allNum += num
	}
	return allNum
}

// UnreadList 未读消息列表
func UnreadList(uid int64, p body.PageTrait) ([]*entity.NewsCommentDetail, int64) {
	allList := make([]*entity.NewsCommentDetail, 0)
	for i := 0; i < int(gorm.GinDb.Split); i++ {
		list := make([]*entity.NewsCommentDetail, 0)
		tableName := "cmf_users_news_comment_" + stringify.ToString(i)
		gorm.GinDb.Table("cmf_users_news n").Select("c.*,u.user_nickname,u.avatar").
			Joins("inner join "+tableName+" c on n.id = c.news_id").
			Joins("left join cmf_users u on c.uid = u.id").
			Where("n.uid = ? and c.is_read = 0 and c.uid != ?", uid, uid).
			Offset(p.GetOffset()).Limit(p.GetLength()).Find(&list)
		allList = append(allList, list...)
	}
	return allList, UnreadNum(uid)
}

// Read 标记已读
func Read(uid int64) {
	for i := 0; i < int(gorm.GinDb.Split); i++ {
		tableName := "cmf_users_news_comment_" + stringify.ToString(i)
		var ids []int64
		gorm.GinDb.Table("cmf_users_news n").
			Joins("left join "+tableName+" c on n.id = c.news_id").
			Where("n.uid = ? and c.is_read = 0 ", uid).Pluck("c.id", &ids)
		if len(ids) > 0 {
			gorm.GinDb.Table(tableName).Where("id in ?", ids).Update("is_read", 1)
		}
	}

}
